package com.tianqi.rms.util;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.kit.HashKit;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.JsTicket;
import com.jfinal.weixin.sdk.api.JsTicketApi;
import com.jfinal.weixin.sdk.api.JsTicketApi.JsApiType;

public abstract class ShakeUtils {

	public static Map<String, Object> Shake (HttpServletRequest request){
		JsTicket jsApiTicket = JsTicketApi.getTicket(JsApiType.jsapi);
		String jsapi_ticket = jsApiTicket.getTicket();
		String nonce_str = create_nonce_str();
		// 注意 URL 一定要动态获取，不能 hardcode.
		String url = "http://" + request.getServerName() // 服务器地址
	
		+ request.getContextPath() // 项目名称
		+ request.getServletPath();// 请求页面或其他地址
		String qs = request.getQueryString(); // 参数
		if (qs != null) {
			url = url + "?" + (request.getQueryString());
		}
		String timestamp = create_timestamp();
		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		//注意这里参数名必须全部小写，且必须有序
		String  str = "jsapi_ticket=" + jsapi_ticket +
				"&noncestr=" + nonce_str +
				"&timestamp=" + timestamp +
				"&url=" + url;
		String signature = HashKit.sha1(str);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("appId", ApiConfigKit.getApiConfig().getAppId());
		map.put("nonceStr", nonce_str);
		map.put("timestamp", timestamp);
		map.put("url", url);
		map.put("signature", signature);
		map.put("jsapi_ticket", jsapi_ticket);
		return map;
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}
}
